package cc.smarnet.caihou.phone.bracts;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;


import java.util.ArrayList;
import java.util.List;

import cc.smarnet.caihou.IPConfig;

import cc.smarnet.caihou.R;
import cc.smarnet.caihou.adapter.BractsAdapter;
import cc.smarnet.caihou.adapter.SpacesItemDecoration;
import cc.smarnet.caihou.entity.Bracts;
import cc.smarnet.caihou.phone.MainPageActivity;
import cc.smarnet.caihou.util.JSONArrayUtil;
import okhttp3.Call;

/**
* 毛产品信息的activity
* */
public class BractsActivity extends AppCompatActivity {
    private RefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private LinearLayout failLoadLinearLayout;
    private LinearLayout noDataLinearLayout;
    private ProgressBar progressBar;
    private ImageButton imageButton;
    private Button addButton;

    private String token;

    private int pageNo = 1;// 取数分页的开始页
    private int pageSize = 4;// 每次取数的数量

    List<Bracts> bractsList = new ArrayList<>();
    BractsAdapter bractsAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bracts);

        getSupportActionBar().hide();//隐藏标题栏

        initViews();
        noDataLinearLayout.setVisibility(View.GONE);// 隐藏暂无数据的信息
        failLoadLinearLayout.setVisibility(View.GONE);// 隐藏数据加载失败的信息

        getToken();
        getBractsInfo();
        // 点击返回按钮的监听
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BractsActivity.this, MainPageActivity.class);
                startActivity(intent);
            }
        });
        // 点击新增按钮的监听
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BractsActivity.this, BractsAddActivity.class);
                startActivity(intent);
            }
        });
        //设置layoutManager,可以设置显示效果，是线性布局、grid布局，还是瀑布流布局(参数是：上下文、列表方向（横向还是纵向）、是否倒叙)
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.addItemDecoration(new SpacesItemDecoration(20));// 设置item的上下左右边距
        recyclerView.setHasFixedSize(true);
        // 这里使用适配器的目的在于使系统不再报‘E/RecyclerView: No adapter attached; skipping layout’的错误
        /*List<Bracts> nullList=new ArrayList<>();
        bractsAdapter=new BractsAdapter(nullList);
        recyclerView.setAdapter(bractsAdapter);*/

        // 下拉刷新，目前在此就不做业务处理了，因为初始时加载的那几条数据就是从第一条开始的查询的
        refreshLayout.setOnRefreshListener(new OnRefreshListener() { //下拉刷新
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh();
            }
        });

        //上拉加载更多
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(final RefreshLayout refreshlayout) {
                progressBar.setVisibility(View.VISIBLE);
                getBractsInfo();
                refreshlayout.finishLoadMore(0);
            }
        });
    }

    public void initViews() {
        refreshLayout = findViewById(R.id.bracts_refreshLayout);
        recyclerView = findViewById(R.id.bracts_recyclerView);
        failLoadLinearLayout = findViewById(R.id.bracts_failLoad_linearLayout);
        noDataLinearLayout = findViewById(R.id.bracts_noData_linearLayout);
        progressBar = findViewById(R.id.bracts_progressBar);
        imageButton = findViewById(R.id.bracts_return);
        addButton = findViewById(R.id.bracts_add_button);
    }

    public void getToken() {
        SharedPreferences sp = getSharedPreferences("userInfo", MODE_PRIVATE);
        token = sp.getString("token", null);
    }

    public void getBractsInfo() {
        String url = IPConfig.baseUrl + "/flower/harvest/list";
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .addParams("pageNo", String.valueOf(pageNo))
                .addParams("pageSize", String.valueOf(pageSize))
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressBar.setVisibility(View.GONE);// 设置加载效果不可见
                        failLoadLinearLayout.setVisibility(View.VISIBLE);// 显示数据加载失败的信息
                    }

                    @Override
                    public void onResponse(String response, int ID) {
                        progressBar.setVisibility(View.GONE);// 设置加载效果不可见
                        failLoadLinearLayout.setVisibility(View.GONE);// 隐藏数据加载失败的信息
                        progressBar.setVisibility(View.GONE);// 设置加载效果不可见
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            String records = JSON.parseObject(result).getString("records");
                            JSONArray jsonArray = JSON.parseArray(records);
                            // 获取毛产品信息并存到bractsList中
                            for (int i = 0; i < jsonArray.size(); i++) {
                                String id = "";
                                String baseName = "";// 来源基地
                                String greenhouseName = "";// 来源大棚
                                String harvestTime = "";// 采摘日期
                                String harvestUser = "";// 采摘人
                                String varietyDictText = "";// 采收品种
                                float harvestWeight = 0;// 采收重量
                                int harvestCount = 0;// 采收支数
                                String createTime = "";// 创建日期

                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                if (jsonObj.containsKey("id")) {
                                    id = jsonObj.getString("id");
                                }
                                if (jsonObj.containsKey("baseName")) {
                                    baseName = jsonObj.getString("baseName");// 来源基地
                                }
                                if (jsonObj.containsKey("greenhouseName")) {
                                    greenhouseName = jsonObj.getString("greenhouseName");// 来源大棚
                                }
                                if (jsonObj.containsKey("harvestTime")) {
                                    harvestTime = jsonObj.getString("harvestTime");// 采摘日期
                                }
                                if (jsonObj.containsKey("harvestUser")) {
                                    harvestUser = jsonObj.getString("harvestUser");// 采摘人
                                }
                                if (jsonObj.containsKey("variety")) {
                                    varietyDictText = jsonObj.getString("variety");// 采收品种
                                }
                                if (jsonObj.containsKey("harvestWeight")) {
                                    harvestWeight = jsonObj.getBigDecimal("harvestWeight").floatValue();// 采收重量
                                }
                                if (jsonObj.containsKey("harvestCount")) {
                                    harvestCount = jsonObj.getInteger("harvestCount");// 采收支数
                                }
                                if (jsonObj.containsKey("createTime")) {
                                    createTime = jsonObj.getString("createTime");// 创建日期
                                }

                                Bracts bracts = new Bracts();
                                bracts.setId(id);
                                bracts.setBaseName(baseName);
                                bracts.setGreenhouseName(greenhouseName);
                                bracts.setHarvestTime(harvestTime);
                                bracts.setHarvestUser(harvestUser);
                                bracts.setVarietyDictText(varietyDictText);
                                bracts.setHarvestWeight(harvestWeight);
                                bracts.setHarvestCount(harvestCount);
                                bracts.setCreateTime(createTime);

                                bractsList.add(bracts);
                            }
                            if (bractsList.size() > 0) {// 如果bractsList中有数据的话就通过bractsAdapter将数据显示在界面上
                                bractsAdapter = new BractsAdapter(getApplicationContext(),bractsList);
                                recyclerView.setAdapter(bractsAdapter);
                            }else {// 否则让暂无数据的信息显示在界面上
                                noDataLinearLayout.setVisibility(View.VISIBLE);
                            }

                            int total=Integer.valueOf(JSON.parseObject(result).getString("total"));//数据在数据库中的总数
                            int current=Integer.valueOf(JSON.parseObject(result).getString("current"));//该次取数是第几次
                            if (current*pageSize>=total){
                                Toast.makeText(BractsActivity.this, "已加载完所有数据", Toast.LENGTH_SHORT).show();
                            }

                            pageNo += 1;
                        }
                    }
                });
    }
}